<template>
	<view class="equip-add-page">
		<view class="well-tip"> 已选择的安装井点：{{ wellInfo.pipNo }} </view>
		<view class="form-wrap">
			<u--form :model="form" ref="uform" labelPosition="left" :labelWidth="104">
				<u-form-item label="设备编号" required borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.equNo" border="none" placeholder="请扫码或输入"></u--input>
					<u-icon slot="right" name="scan" color="#3576F2" size="80rpx" @click="handleScan"></u-icon>
				</u-form-item>
				<u-form-item label="所属区域" borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.areaName" disabled disabledColor="#fff" border="none"
						placeholder="请选择所属区域"></u--input>
				</u-form-item>
				<u-form-item label="所属道路" borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.street" disabled disabledColor="#fff" border="none" placeholder="请输入所属道路"></u--input>
				</u-form-item>
				<u-form-item label="设备名称" borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.equName" disabled disabledColor="#fff" border="none" placeholder="请输入设备名称"></u--input>
				</u-form-item>
				<u-form-item label="类型" required borderBottom @click="
            equTypeShow = true;
            hideKeyboard();
          " customStyle="height:80rpx;">
					<u--input :value="equTypeValue" disabled disabledColor="#fff" border="none" placeholder="请选择设备类型"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="补偿值" :required="[1,7].includes(+form.equType)" borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.compensate" type="number" border="none" placeholder="请输入补偿值"></u--input>
				</u-form-item>
				<u-form-item label="经纬度" borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.position" disabled disabledColor="#fff" border="none"></u--input>
				</u-form-item>
				<u-form-item label="设备经纬度" borderBottom customStyle="height:80rpx;">
					<u--input v-model="form.equipPosition" disabled disabledColor="#fff" border="none"></u--input>
					<u-icon slot="right" name="map" size="60rpx" @click="handleResetGeo"></u-icon>
				</u-form-item>
				<u-form-item label="归属状态" borderBottom @click="
            belongShow = true;
            hideKeyboard();
          " customStyle="height:80rpx;">
					<u--input :value="equBelongValue" disabled disabledColor="#fff" border="none"
						placeholder="请选择归属状态"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="设备厂家" required borderBottom disabledColor="#fff" customStyle="height:80rpx;">
					<u-radio-group v-model="form.brand" placement="row">
						<u-radio :name="1" label="自研" :size="16" :labelSize="16" :customStyle="{marginRight: '8px'}"></u-radio>
						<u-radio :name="2" label="采购" :size="16" :labelSize="16"></u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="安装图片" borderBottom disabledColor="#fff" customStyle="height:190rpx;">
					<u-upload width="200rpx" height="200rpx" :previewFullImage="true" :fileList="tp" name="tp" @afterRead="afterRead"
						@delete="deletePic" :multiple="false" :maxCount="1">
					</u-upload>
				</u-form-item>
			</u--form>
		</view>
		<view class="page-btn-wrap">
			<view class="btn-item">
				<u-button type="primary" text="提交" customStyle="margin: auto 0" @click="submit"></u-button>
			</view>
		</view>
		<u-picker :show="belongShow" keyName="name" title="归属状态" :columns="[equBelongList]" @cancel="belongShow = false"
			@confirm="belongSelect"></u-picker>
		<u-picker :show="equTypeShow" keyName="name" title="类型" :columns="[equTypeList]" @cancel="equTypeShow = false"
			@confirm="equTypeSelect"></u-picker>
	</view>
</template>
<script>
	import {
		equipAdd,
		addEquipOperateLog
	} from '@/api/equip.js';
	import {
		getDictItemInfo
	} from '@/api/system';
	import {
		equBelongList
	} from '@/config/enumeration.js';
	import {
		commonUploadPic
	} from '@/api/houseInfo.js'

	export default {
		data() {
			return {
				wellInfo: {},
				tp: [],
				form: {
					pipPointNo: '', // 带入 管点编号 pipNo
					pointArea: '', // 带入 管点区域id areaId
					pointCode: '', // 带入 associationPosPointNo
					equNo: '', // 设备编号 必填项
					areaName: '', // 带入 areaId_dictText
					street: '', // 带入 street
					equName: '', // 设备名称 自动生成：管点区域+管点编号
					equType: '', // 设备类型 必填项 字典值
					compensate: '', // 补偿值
					position: '', // 带入 longitude + latitude
					equipPosition: '', // 带入设备 installLongitude + installLatitude
					equBelong: '', // 归属状态 字典-归属状态  1售卖 2租赁 3临时
					installLatitude: '',
					installLongitude: '',
					brand: '',
					picData: '',
				},
				eventChannel: null,
				equTypeShow: false,
				equTypeValue: '',
				belongShow: false,
				equBelongValue: '',
				equTypeList: [], // 设备类型列表-字典值列表
				equBelongList, // 归属状态
			};
		},
		onLoad(option) {
			const eventChannel = this.getOpenerEventChannel();
			this.eventChannel = eventChannel;
			eventChannel.on('sendWellInfo', (data) => {
				this.wellInfo = data;
				console.log('wellInfo', data);
				this.init(data);
			});
		},
		onUnload() {
			this.eventChannel.off('sendWellInfo');
		},
		methods: {
			init(data) {
				this.form.pipPointNo = data.pipNo;
				this.form.pointArea = data.areaId;
				this.form.pointCode = data.associationPosPointNo;
				this.form.areaName = data.areaId_dictText || '-';
				this.form.street = data.street || '-';
				this.form.equName = (data.street || '') + (data.pipNo || '') || '-';
				this.form.position = data.longitude ? data.longitude + '，' + data.latitude : '-';
				this.form.installLatitude = data.latitude || '';
				this.form.installLongitude = data.longitude || '';
				this.form.brand = data.brand || '';
				//字典 设备类型 	ps_equ_type
				this.getDictListFun('ps_equ_type');
			},
			async submit() {
				try {
					const {
						equNo,
						equType,
						compensate,
						equBelong,
						brand
					} = this.form;
					if ([1, 7].includes(+equType) && !compensate) {
						uni.showToast({
							icon: 'error',
							title: '请输入补偿值',
						});
						return;
					}
					if (!(equNo && equType && equBelong && brand)) {
						uni.showToast({
							icon: 'error',
							title: '请先完成表单项（设备编号、设备类型、归属状态、设备厂家）',
						});
						return;
					}
					const params = {
						...this.form,
						sim: equNo,
						picData: JSON.stringify(this.tp.map(item => item.url).map(url =>
							({
								name: url.substring(url.lastIndexOf('/') + 1),
								path: url
							}))),
					};
					const res = await equipAdd(params);
					if (res.data.success) {
						const {
							pipPointNo,
							equNo,
							equType
						} = this.form;
						const operationParams = {
							pointNo: pipPointNo,
							equNo,
							equType,
							status: 1,
							operateType: 1,
							operateSource: 2,
							operateTime: new Date().format('yyyy-MM-dd hh:mm:ss'),
						};
						await addEquipOperateLog(operationParams);
						uni.showToast({
							title: '已提交',
						});
						uni.navigateBack({
							success: () => {
								this.eventChannel.emit('refresh');
							},
						});
					} else {
						uni.showToast({
							title: res.data.message || '请求失败',
							icon: 'error',
						});
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			async getDictListFun(dictCode) {
				try {
					const res = await getDictItemInfo({
						dictCode,
					});
					this.equTypeList = (res.data.result || []).map((x) => {
						return {
							name: x.itemText,
							label: x.itemText,
							value: x.itemValue,
						};
					});
				} catch (e) {
					//TODO handle the exception
				}
			},
			handleResetGeo() {
				uni.getLocation({
					type: 'wgs84',
					altitude: true,
					isHighAccuracy: true,
					success: (res) => {
						const latitude = (res.latitude + '').length > 11 ? res.latitude.toFixed(8) : res.latitude;
						const longitude = (res.longitude + '').length > 12 ? res.longitude.toFixed(8) : res.longitude;
						this.form.installLatitude = latitude || '';
						this.form.installLongitude = longitude || '';
						this.form.equipPosition = longitude + '，' + latitude;
						uni.showToast({
							title: '已成功重置经纬度',
						});
					},
				});
			},
			belongSelect(res) {
				const selectItem = res.value[0];
				this.form.equBelong = selectItem.type;
				this.equBelongValue = selectItem.name;
				this.belongShow = false;
			},
			equTypeSelect(res) {
				const selectItem = res.value[0];
				this.form.equType = selectItem.value;
				this.equTypeValue = selectItem.name;
				this.equTypeShow = false;
			},
			handleScan() {
				// 允许从相机和相册扫码
				uni.scanCode({
					scanType: ['qrCode'],
					success: (res) => {
						if (res.result) {
							this.form.equNo = res.result;
						}
					},
					fail: (res) => {
						uni.showToast({
							title: '未识别到二维码',
						});
					},
				});
			},
			hideKeyboard() {
				uni.hideKeyboard();
			},
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[event.name].length
				lists.map((item) => {
					this[event.name].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[event.name][fileListLen]
					this[event.name].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			async uploadFilePromise(url) {
				const res = await commonUploadPic(url)
				console.log(res, 'uploadHttp')
				let d = JSON.parse(res.data)
				if (d.code == 200) {
					return d.result.picUrl
				}
			},
			// 删除图片
			deletePic(event) {
				this.tp.splice(event.index, 1)
			},
		},
	};
</script>
<style lang="scss" scoped>
	.equip-add-page {
		min-height: 100vh;
		background-color: #fff;
	}

	.well-tip {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		height: 74rpx;
		padding: 0 32rpx;
		background: #dae7ff;
		font-weight: 400;
		font-size: 30rpx;
		color: #3576f2;
	}

	.form-wrap {
		padding: 0 32rpx;
		margin-bottom: 180rpx;
	}

	.page-btn-wrap {
		position: fixed;
		display: flex;
		bottom: 0;
		width: 100%;
		height: 166rpx;
		box-shadow: 0 -4rpx 24rpx 0 #00000014;
		background: white;
		z-index: 99;
	}

	.btn-item {
		padding: 16rpx 32rpx 0 32rpx;
		width: 100%;
		height: 100%;
	}
</style>